package com.iocoder.yudao.module.erp.mapper.stock;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iocoder.yudao.module.erp.controller.admin.stock.vo.stock.ErpProductStockPageVo;
import com.iocoder.yudao.module.erp.model.stock.ErpStockDO;
import org.apache.ibatis.annotations.Mapper;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * ERP 库存 Mapper
 *
 * @author 三大爷
 */

@Mapper
public interface ErpProductStockMapper extends BaseMapperX<ErpStockDO> {

   default PageResult<ErpStockDO> selectPage(ErpProductStockPageVo pageReqVO){

      return selectPage(pageReqVO,new LambdaQueryWrapperX<ErpStockDO>()
              .eqIfPresent(ErpStockDO::getProductId,pageReqVO.getProductId())
              .eqIfPresent(ErpStockDO::getWarehouseId,pageReqVO.getWarehouseId())
              .orderByDesc(ErpStockDO::getId)
      );

   }

   default ErpStockDO selectByProductIdAndWarehouseId(Long productId, Long warehouseId){
       return selectOne(ErpStockDO::getProductId, productId,
               ErpStockDO::getWarehouseId, warehouseId);
   }

   default BigDecimal selectSumByProductId(Long productId){
      // SQL sum 查询
      List<Map<String, Object>> result = selectMaps(new QueryWrapper<ErpStockDO>()
              .select("SUM(count) AS sumCount")
              .eq("product_id", productId));
      // 获得数量
      if (CollUtil.isEmpty(result)) {
         return BigDecimal.ZERO;
      }
      return BigDecimal.valueOf(MapUtil.getDouble(result.get(0), "sumCount", 0D));
   }
}
